package com.guli.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.guli.cart.conf.CartInterceptor;
import com.guli.cart.feign.FeignSkuInfo;
import com.guli.cart.service.CartService;
import com.guli.cart.vo.CartItemVo;
import com.guli.cart.vo.CartVo;
import com.guli.cart.vo.UserVo;
import com.guli.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author WZH
 * @title: CartServiceImpl
 * @projectName gulimall-java
 * @description:
 * @date 2022/1/19
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FeignSkuInfo feignSkuInfo;

    @Override
    public void addToCart(String skuId, Integer num) {
        //添加购物车存入redis
        //1.获取用户（登录用户/临时用户）
        BoundHashOperations userOps=getUserOps();
        //判断要添加的数据
        CartItemVo o = (CartItemVo) userOps.get(skuId);
        //redis有+num
        if (o!=null){
            o.setCount(o.getCount()+num);
            userOps.put(skuId,o);
        }else {
            //redis无 添加redis
            R r=feignSkuInfo.getCart(skuId);
            CartItemVo cartItemVo = r.getData(new TypeReference<CartItemVo>() { });
            cartItemVo.setCount(num);
            userOps.put(skuId,cartItemVo);
        }
    }

    @Override
    public CartItemVo getCart(String skuId) {

        return (CartItemVo) getUserOps().get(skuId);
    }

    @Override
    public CartVo getCartVo() {
        //判断 游客/已登录 用户
        UserVo userVo = CartInterceptor.threadLocal.get();
        CartVo cartVo = new CartVo();
        List<CartItemVo> values = redisTemplate.boundHashOps("gulimall:cart:"+userVo.getUserKey()).values();
        List<CartItemVo> cartItemVos = getCartItemVos(values);
        if (!StringUtils.isEmpty(userVo.getUserId())){
            //临时 添加到 登录
            redisTemplate.boundHashOps("gulimall:cart:"+userVo.getUserId()).values();
            values.stream().forEach(item->{
                addToCart(item.getSkuId().toString(),item.getCount());
            });
            //清空 临时
            redisTemplate.delete("gulimall:cart:"+userVo.getUserKey());
            //添加数据
            List<CartItemVo> ids = redisTemplate.boundHashOps("gulimall:cart:"+userVo.getUserId()).values();
            List<CartItemVo> idss = getCartItemVos(ids);
            cartVo.setItems(idss);
        }else {
            cartVo.setItems(cartItemVos);
        }
        return cartVo;
    }

    @Override
    public void updCheck(Long skuId, Boolean check) {
        BoundHashOperations userOps = getUserOps();
        CartItemVo o = (CartItemVo) userOps.get(skuId.toString());
        o.setCheck(check);
        userOps.put(skuId.toString(),o);
    }

    @Override
    public void updNum(Long skuId, Integer num) {
        BoundHashOperations userOps = getUserOps();
        CartItemVo o = (CartItemVo) userOps.get(skuId.toString());
        o.setCount(num);
        userOps.put(skuId.toString(),o);
    }

    @Override
    public void del(Long skuId) {
        BoundHashOperations userOps = getUserOps();
        userOps.delete(skuId.toString());
    }

    @Override
    public R getCartCheckList() {
        //获取当前用户的购物车
        BoundHashOperations userOps = getUserOps();
        List<CartItemVo> values = userOps.values();
        //获取选中的商品
        List<CartItemVo> items = values.stream().filter(e -> e.getCheck()).map(e->{
            //(feign调用)查询价格
            R r = feignSkuInfo.getCart(e.getSkuId().toString());
            CartItemVo data = r.getData(new TypeReference<CartItemVo>() { });
            e.setPrice(data.getPrice());
            return e;
        }).collect(Collectors.toList());
        return R.ok().setData(items);
    }

    private List<CartItemVo> getCartItemVos(List<CartItemVo> values){
        return values.stream().map(item -> {
            return item;
        }).collect(Collectors.toList());
    }

    public BoundHashOperations getUserOps() {
        //判断userid
        UserVo userVo = CartInterceptor.threadLocal.get();
        if (!StringUtils.isEmpty(userVo.getUserId())){
            return redisTemplate.boundHashOps("gulimall:cart:"+userVo.getUserId());
        }
        return redisTemplate.boundHashOps("gulimall:cart:"+userVo.getUserKey());
    }
}
